package com.shop.service;

import java.util.ArrayList;
import java.util.List;

import com.shop.dao.OrderDao;
import com.shop.domain.Order;
import com.shop.domain.OrderItem;
import com.shop.domain.User;

public class OrderService {

	public void addOrders(Order order) {
		new OrderDao().addOrder(order);
	}
//重要
	public List<Order> findOrders(User user) {
		OrderDao dao = new OrderDao();
		List<Order> orders = new ArrayList<Order>();
		if (user.getRole().equals("admin")) {
			orders = dao.findAll();
			for (Order order : orders) {
				List<OrderItem> items = dao.findOrderItems(order);
				order.setOrderItems(items);
			}
		} else {
			orders = dao.findByUser(user);
			for (Order order : orders) {
				List<OrderItem> items = dao.findOrderItems(order);
				order.setOrderItems(items);
			}
		}
		return orders;
	}

	public Order findOrderByID(String id) {
		return new OrderDao().findOrderByID(id);
	}

	public void delOrderByID(String id) {
		new OrderDao().delOrderByID(id);
	}

	public void delOrderByID(String id, User user) {
		Order order = findOrderByID(id);
		
		if (order == null) {
			throw new RuntimeException("订单不存在，不能删除");
		}
		if (order.getState() != 0) {
			throw new RuntimeException("订单已经支付，不能删除");
		}
		if (order.getUser_id() != user.getId()) {
			throw new RuntimeException("不是您产生的订单，不能删除");
		}
		
		delOrderByID(id);

	}

	public void pay(String r6_Order) {
		new OrderDao().updateState(r6_Order);
	}

}
